import random
import requests
import json
from requests.auth import HTTPBasicAuth

# 需要新增的数据量
data = 1

api_key = "xxxxxxxxx"
api_secret = "xxxxxxx"
form_token = "xxxxxxxx"

url = "https://sc.jinshuju.net/api/v1/forms/" + form_token


# 初始化json file
def init_json_file():
	with open("./data.json", "r+", encoding="utf-8") as jsonFile:
		jsonFile.truncate()
		json.dump({}, jsonFile)

# 创建姓名
def create_name():
	LastName = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻水云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳鲍史唐费岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅卞齐康伍余元卜顾孟平" \
               "黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计成戴宋茅庞熊纪舒屈项祝董粱杜阮席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田胡凌霍万柯卢莫房缪干解应宗丁宣邓郁单杭洪包诸左石崔吉" \
               "龚程邢滑裴陆荣翁荀羊甄家封芮储靳邴松井富乌焦巴弓牧隗山谷车侯伊宁仇祖武符刘景詹束龙叶幸司韶黎乔苍双闻莘劳逄姬冉宰桂牛寿通边燕冀尚农温庄晏瞿茹习鱼容向古戈终居衡步都耿满弘国文东殴沃曾关红游盖益桓公晋楚闫"
	FirstName = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽"\
    			"伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘"
	MiddleName = "中笑贝凯歌易仁器义礼智信友上都卡被好无九加电金马钰玉忠孝"
	LastName_name =LastName[random.choice(range(len(LastName)))]
	FirstName_name = FirstName[random.choice(range(len(FirstName)))]
	if random.choice(range(2)) > 0:
		MiddleName_name = MiddleName[random.choice(range(len(MiddleName)))]
		name = LastName_name + MiddleName_name + FirstName_name
	else:
		name = LastName_name + FirstName_name
	return name

# 创建手机号
def create_mobilephone():
	prelist = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139","147", "150", "151", "152", "153", "155", "156", "157", "158", "159","186", "187", "188", "189", "199"]
	phonenumber = random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))
	return phonenumber

# 创建邮箱
def create_email():
	emailtype = ["@qq.com", "@163.com", "@126.com", "@189.com"]
	rang = random.randint(4, 10)
	num = "0123456789qbcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ"
	email = "".join(random.choice(num) for i in range(rang)) + random.choice(emailtype)
	return email

# 创建电话号码
def create_telephone():
	prelist = ["0817", "0816", "0202", "0519", "0575", "0755"]
	telephonenumber = random.choice(prelist)+"-"+"".join(random.choice("0123456789") for i in range(7))
	return telephonenumber

# 创建随机数字
def create_number():
	if random.choice(range(2)) > 0:
		number = random.uniform(0.00,10000.00)
	else:
		number = random.randint(0,10000)
	return number

# 创建单选
def create_single_choice(result_json,i,field):
	# field = "field_" + str(i+1)
	item = random.randint(0,len(result_json['fields'][i][field]['choices'])-1)
	choice = result_json['fields'][i][field]['choices'][item]['value']
	return choice

# 创建多选
def create_multiple_choice(result_json,i,field):
	field_choice = []
	# field = "field_" + str(i+1)
	item = len(result_json['fields'][i][field]['choices'])
	field_number = i
	for i in range(0,item):
		field_choice.append(result_json['fields'][field_number][field]['choices'][i]['value'])
	choices = random.sample(field_choice,random.randint(1,item))
	return choices

# 创建多级下拉框选项
def create_cascade_drop_down(result_json,i,field):
	cascade = 2
	if "sub_choices" in result_json['fields'][i][field]['choices'][0]['sub_choices'][0]:
		cascade = cascade +1
		if "sub_choices" in result_json['fields'][i][field]['choices'][0]['sub_choices'][0]['sub_choices'][0]:
			cascade = cascade + 1
		else:
			cascade = cascade
	else:
		cascade = 2
	if cascade == 2:
		level1_item = random.randint(0,len(result_json['fields'][i][field]['choices'])-1)
		level2_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'])-1)
		level1 = result_json['fields'][i][field]['choices'][level1_item]['value']
		level2 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['value']
		cascade_choice = {"level_1":level1,"level_2":level2}
	if cascade == 3:
		level1_item = random.randint(0,len(result_json['fields'][i][field]['choices'])-1)
		level2_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'])-1)
		level3_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'])-1)
		level1 = result_json['fields'][i][field]['choices'][level1_item]['value']
		level2 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['value']
		level3 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'][level3_item]['value']
		cascade_choice = {"level_1":level1,"level_2":level2,"level_3":level3}
	if cascade == 4:
		level1_item = random.randint(0,len(result_json['fields'][i][field]['choices'])-1)
		level2_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'])-1)
		level3_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'])-1)
		level4_item = random.randint(0,len(result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'][level3_item]['sub_choices'])-1)
		level1 = result_json['fields'][i][field]['choices'][level1_item]['value']
		level2 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['value']
		level3 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'][level3_item]['value']
		level4 = result_json['fields'][i][field]['choices'][level1_item]['sub_choices'][level2_item]['sub_choices'][level3_item]['sub_choices'][level4_item]['value']
		cascade_choice = {"level_1":level1,"level_2":level2,"level_3":level3,"level_4":level4}
	return cascade_choice

# 创建评分
def create_rating(result_json,i,field):
	rating_max = int(result_json['fields'][i][field]['rating_max'])
	rating = random.randint(0,rating_max)
	return rating

# 创建nps
def create_nps():
	nps = random.randint(0,10)
	return nps

# 创建时间
def create_time(result_json,i,field):
	hour = random.randint(0,23)
	minute = random.randint(0,59)
	second = random.randint(0,59)
	if "include_second" in result_json['fields'][i][field]:
		time = {"hour":hour,"minute":minute,"second":second}
	else:
		time = {"hour":hour,"minute":minute}

# 创建日期（年月日）
def create_date():
	year = random.randint(2000,2022)
	month = random.randint(1,12)
	if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
		if month == 2:
			day = random.randint(1,29)
		if month in [1,3,5,7,8,10,12]:
			day = random.randint(1,31)
		if month in [4,6,9,11]:
			day = random.randint(1,30)
	else:
		if month == 2:
			day = random.randint(1,28)
		if month in [1,3,5,7,8,10,12]:
			day = random.randint(1,31)
		if month in [4,6,9,11]:
			day = random.randint(1,30)
	date = str(year)+"-"+str(month)+"-"+str(day)
	return date

# 创建日期时间（年月、年月日、年月日时分、年月日时分秒）
def create_date_time(result_json,i,field):
	# field = "field_" + str(i+1)
	if result_json['fields'][i][field]['precision'] == "month":
		year = random.randint(2000,2022)
		month = random.randint(1,12)
		date_time = str(year)+"-"+str(month)
	if result_json['fields'][i][field]['precision'] == "day":
		date_time = create_date()
	if result_json['fields'][i][field]['precision'] == "minute":
		hour = random.randint(0,23)
		minute = random.randint(0,59)
		date_time = create_date() + " " + str(hour) + ":" + str(minute)
	if result_json['fields'][i][field]['precision'] == "second":
		hour = random.randint(0,23)
		minute = random.randint(0,59)
		second = random.randint(0,59)
		date_time = create_date() + " " + str(hour) + ":" + str(minute) + ":" + str(second)
	return date_time

# 创建矩阵单选
def create_likert(result_json,i,field):
	statements_len = len(result_json['fields'][i][field]['statements'])
	likert = {}
	for m in range(0,statements_len):
		statements = result_json['fields'][i][field]['statements'][m]['value']
		choice_item = random.randint(0,len(result_json['fields'][i][field]['choices'])-1)
		choice = result_json['fields'][i][field]['choices'][choice_item]['value']
		data = {statements:choice}
		likert.update(data)
	print(likert)
	return likert

# 创建矩阵量表
def create_matrix_scale(result_json,i,field):
	statements_len = len(result_json['fields'][i][field]['statements'])
	rating_max = result_json['fields'][i][field]['dimensions'][0]['field_1']['rating_max']
	matrix_scale = {}
	for m in range(0,statements_len):
		statements = result_json['fields'][i][field]['statements'][m]['value']
		rating = random.randint(0,rating_max)
		data = {statements:{'field_1':rating}}
		matrix_scale.update(data)
	print(matrix_scale)
	return matrix_scale

# 获取表单结构
def get_form_structure():
	rtn = requests.get(url, auth=HTTPBasicAuth(api_key, api_secret))
	result = rtn.text
	result_json = json.loads(result)
	form_field_volume = len(result_json['fields'])
	fields = []
	for i in range(0,form_field_volume):
		for key in result_json['fields'][i].items():
			fields.append(key[0])
	# return result_json,form_field_volume,fields
	form_structure_data = [result_json,form_field_volume,fields]
	return form_structure_data

# 构造新增数据的json file
def create_json_file():
	form_structure_data = get_form_structure()
	result_json = form_structure_data[0]
	form_field_volume = form_structure_data[1]
	fields = form_structure_data[2]
	with open("./data.json", "r+", encoding='utf-8') as jsonFile:
		data = json.load(jsonFile)
		for i in range(0,form_field_volume):
	    	# field = "field_" + str(i+1)
			field = fields[i]
			if result_json['fields'][i][field]['label'] == "姓名":
				name = create_name()
				data[field] = name
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "mobile":
				phone = create_mobilephone()
				data[field] = phone
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "email":
				email = create_email()
				data[field] = email
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "phone":
				telephone = create_telephone()
				data[field] = telephone
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "single_choice" or result_json['fields'][i][field]['type'] == "drop_down":
				choice = create_single_choice(result_json,i,field)
				data[field] = choice
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "multiple_choice":
				choices = create_multiple_choice(result_json,i,field)
				data[field] = choices
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "cascade_drop_down":
				cascade_choice = create_cascade_drop_down(result_json,i,field)
				data[field] = cascade_choice
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "number":
				number = create_number()
				data[field] = number
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "rating":
				rating = create_rating(result_json,i,field)
				data[field] = rating
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "nps":
				nps = create_nps()
				data[field] = nps
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "time":
				time = create_time(result_json,i,field)
				data[field] = time
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "date":
				date = create_date()
				data[field] = date
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "date_time":
				date = create_date_time(result_json,i,field)
				data[field] = date
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "likert":
				date = create_likert(result_json,i,field)
				data[field] = date
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
			if result_json['fields'][i][field]['type'] == "matrix_scale":
				date = create_matrix_scale(result_json,i,field)
				data[field] = date
				jsonFile.seek(0)
				json.dump(data, jsonFile, ensure_ascii=False)
	jsonFile.close()

# 使用V1接口新增数据
def create_entry():
	create_json_file()
	with open("./data.json", "r", encoding='utf-8') as jsonFile:
		json_file = json.load(jsonFile)
        # print(json_file)
		rtn = requests.post(url, json=json_file, auth=HTTPBasicAuth(api_key, api_secret))
		print(rtn.json())
		jsonFile.close()

if __name__ == '__main__':
	for i in range(0,data):
		init_json_file()
		create_entry()
		print("已新增"+ str(i+1) + "条数据\n")
